import { defineStore } from 'pinia'
import { projectsApi } from '@/api/projects'

export const useProjectStore = defineStore('project', {
  state: () => ({
    projects: [],
    activeFileId: null,
    currentDependencyData: null,
    loading: false,
    error: null,
    currentView: 'list',  // 'list' 或 'graph'
    projectCurrentFiles: new Map()  // key: projectId, value: fileId
  }),

  getters: {
    currentProject: (state) => {
      if (!state.activeFileId) return null
      return state.projects.find(project => 
        project.files.some(file => file.id === state.activeFileId)
      )
    },
    currentFile: (state) => {
      if (!state.activeFileId) return null
      for (const project of state.projects) {
        const file = project.files.find(f => f.id === state.activeFileId)
        if (file) return file
      }
      return null
    }
  },

  actions: {
    setActiveFileId(fileId) {
      this.activeFileId = fileId
    },

    // 设置当前视图
    setCurrentView(view) {
      this.currentView = view
    },

    setCurrentProject(project) {
      this.currentProject = project
    },

    // 新增：设置项目当前显示的文件
    setProjectCurrentFile(projectId, fileId) {
      this.projectCurrentFiles.set(projectId, fileId);
    },

    // 新增：获取项目当前显示的文件
    getProjectCurrentFile(projectId) {
      return this.projectCurrentFiles.get(projectId);
    },

    // 加载项目列表
    async fetchProjects() {
      this.loading = true
      this.error = null
      try {
        const projects = await projectsApi.getProjects()
        this.projects = projects
        
        // 为每个项目设置默认显示的文件（最新版本）
        projects.forEach(project => {
          if (project.files.length > 0) {
            const latestFile = [...project.files]
              .sort((a, b) => parseFloat(b.version) - parseFloat(a.version))[0];
            this.setProjectCurrentFile(project.id, latestFile.id);
          }
        });
      } catch (error) {
        this.error = error.message
        throw error
      } finally {
        this.loading = false
      }
    },

    // 加载依赖项
    async fetchDependencies(fileName) {
      this.loading = true
      this.error = null
      try {
        const dependencyData = await projectsApi.getFileDependencies(fileName)
        if (dependencyData) {
          this.currentDependencyData = {
            nodes: dependencyData.nodes,
            dependencies: dependencyData.dependencies
          }
        }
      } catch (error) {
        this.error = error.message
        throw error
      } finally {
        this.loading = false
      }
    },

    // 重置依赖数据
    resetDependencyData() {
      this.currentDependencyData = null
    }
  }
}) 